//<% @Page  %>

using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web; 
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using WebApplication;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.XPath;
using System.IO;

namespace WebApplication
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public partial class InitialPage : System.Web.UI.Page
	{
	

		private void refresh_Page ()
		{
			string [] nTest = { "", "", "" };

			int nSelectedIndex = gamesLB.SelectedIndex;

			gamesLB.AutoPostBack = true;
			Global.GetGames (ref nTest);
			gamesLB.DataSource = nTest;
			gamesLB.DataBind ();
			gamesLB.SelectedIndex = nSelectedIndex;
			string sTemp;
			int nGames =  Global.getTotalGames ();
			sTemp = "Games: " + nGames;
			totalGames.Text = sTemp;

			if (-1 == nSelectedIndex)
			{
				joinGamePB.Enabled = false;
			}
			else
			{
				joinGamePB.Enabled = true;
			}
		}

		protected void Page_Load(object sender, System.EventArgs e)
		{
			this.refresh_Page ();
		}
/*
 * protected void Page_Unload(object sender, System.EventArgs e)
        {

        }
*/

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion


		protected void NewGameButton_Click(object sender, System.EventArgs e)
		{
			string sPlayerName = PlayerName.Text;
			string sNewGameName = createNewGame (sPlayerName);
			joinGame (sPlayerName, sNewGameName);
		}

		private string createNewGame (string sPlayerName)
		{
			string sGameName = sPlayerName + "'s game";
			string sOriginalName = sGameName;
			int i = 0;

			while (duplicateGameName (sGameName))
			{
				i++;
				sGameName = sOriginalName + "_" + i;
			}

			WebApplication.Global.addGame (sGameName, sPlayerName, this.Server.MachineName, MapPathSecure (TemplateSourceDirectory));
			return sGameName;
	}

		bool duplicateGameName (string sGameName)
		{
			return WebApplication.Global.doesGameExist (sGameName);
		}

		private void joinGame (string sPlayerName, string sGameName)
		{
			string sError = "";

			if (!WebApplication.Global.addPlayer (sGameName, sPlayerName, ref sError))
			{
				Response.BufferOutput = true;
				Game game = Global.getGame (sGameName);
				Session["GameName"] = sGameName;
				Session["PlayerName"] = sPlayerName;
//				Response.Redirect("http://localhost/1856/1856 Start Game.aspx");

                if (game.RejoinedPlayers != null)
                {
                    game.RejoinedPlayers.Add (sPlayerName);
                    Response.Redirect("Restart Game.aspx");
                }
                else
                {
				    Response.Redirect("1856 Start Game.aspx");
				}
			}
			else
			{
				statusLabel.Text = sError;
			}
		}

		protected void joinGamePB_Click(object sender, System.EventArgs e)
		{
			string sPlayerName = PlayerName.Text;
			
			if (sPlayerName.ToLower ().Equals ("enter your name"))
			{
                statusLabel.Text = "You must enter your name before joining a game.";
                return;
			}
			
			string sGameName;

			if (gamesLB.SelectedIndex != -1)
			{
				sGameName = gamesLB.SelectedItem.ToString ();
				joinGame (sPlayerName, sGameName);
			}
			else
			{
				statusLabel.Text = "No game selected.  You must select a game before joining a game.";
			}
		}

		protected void gamesLB_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (gamesLB.SelectedIndex != -1)
			{
				joinGamePB.Enabled = true;
			}
			else
			{
				joinGamePB.Enabled = false;
			}
		}

        protected void RestoreButton_Click(object sender, EventArgs e)
        {
            if (this.FileUpload1.HasFile)
            {
                string sFileName = this.FileUpload1.FileName;
                string sFileExtension = System.IO.Path.GetExtension (sFileName).ToLower ();
                
                //if (sFileExtension.Equals (".xml"))
                { // let loading logic dictate file extensions
                    string sPlayerName = PlayerName.Text; 
                    RestoreGame(sPlayerName);
                }
                //else
                //{
                //    statusLabel.Text = "You must select a .Xml file to restore.";
                //}
            }
            else
            {
                statusLabel.Text = "You must select a game before restoring a game.";
            }
        }

		private void RestoreGame(string sPlayerName)
		{
			string sFullPath = this.FileUpload1.PostedFile.FileName;
			Game restoredGame;

			try
			{
				restoredGame = Game.LoadGame(sFullPath);
			}
			catch (Exception ex)
			{
				System.Diagnostics.Trace.WriteLine(ex.ToString());
				statusLabel.Text = "LoadGame failed:\n" + ex.ToString();
				return;
			}

/*
			if (!restoredGame.Creator.Equals(sPlayerName, StringComparison.OrdinalIgnoreCase))
			{
				statusLabel.Text = "Only the original creator, " + restoredGame.Creator + ", may restore this game.";
				return;
			}
 */
 
            sPlayerName = restoredGame.Creator;
			statusLabel.ForeColor = Color.Blue;
			statusLabel.Text = "Restoring game... ";

			// JoeB - 10/16/2007 crude attempt to get the game going
			
			Session["GameName"] = restoredGame.GameName;
			Session["PlayerName"] = sPlayerName;
            WebApplication.Global.addGame(restoredGame);
			
			if (restoredGame.Players.Count == 1)
			{
                if (restoredGame.InStockRound())
                {
                    Response.Redirect("StockRound.aspx");
                }
                else
                {
                    Response.Redirect("OperatingRound2.aspx");
                }			
			}
			else 
			{
			    restoredGame.Started = false;
			    restoredGame.RejoinedPlayers = new StringCollection ();
			    restoredGame.RejoinedPlayers.Add (sPlayerName);
                Response.Redirect("Restart Game.aspx");
			}
		}

	}
}
